package global

import (
	"bytes"
	"io"
	"log"
	"net/http"

	"github.com/ethereum/go-ethereum/ethclient"
)

const BSC_DEV_URL string = "http://localhost:8545"
const BSC_TEST_URL string = "https://data-seed-prebsc-1-s2.bnbchain.org:8545"
const BSC_TEST2_URL string = "https://bsc-testnet-dataseed.bnbchain.org:8545"
const BSC_MAIN_URL string = "https://bsc-dataseed.bnbchain.org"
const BSC_MAIN2_URL string = "https://bsc-dataseed.binance.org"
const BSC_MAIN3_URL string = "https://binance.llamarpc.com"
const BSC_TEST_API_URL string = "https://api-testnet.bscscan.com"
const BSC_MAIN_API_URL string = "https://api.bscscan.com"
const ETH_MAIN_API_URL string = "https://api.arbiscan.io"

var client *ethclient.Client

func GetBSCUrl() string {
	switch DEFAULT_ENV {
	case DEV:
		return BSC_DEV_URL
	case TEST:
		return BSC_TEST_URL
	case UAT:
		return BSC_TEST_URL
	case PROD:
		return BSC_MAIN_URL
	}
	return BSC_MAIN_URL
}

func GetBSCApiUrl() string {
	switch DEFAULT_ENV {
	case DEV:
		return BSC_TEST_API_URL
	case TEST:
		return BSC_TEST_API_URL
	case UAT:
		return BSC_TEST_API_URL
	case PROD:
		return BSC_MAIN_API_URL
	}
	return BSC_MAIN_API_URL
}

func InitClient() {
	url := GetBSCUrl()
	c, err := ethclient.Dial(url)
	if err != nil {
		log.Println("dial error", err)
		return
	}
	client = c
}

func Client() *ethclient.Client {
	return client
}

func HttpGet(u string) ([]byte, error) {
	req, err := http.NewRequest("GET", u, nil)
	if err != nil {
		return nil, err
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return bodyBytes, nil
}

func HttpPost(url string, req []byte) ([]byte, error) {
	request, err := http.NewRequest("POST", url, bytes.NewReader(req))
	if err != nil {
		log.Println("http new request error")
		return nil, err
	}
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Connection", "Keep-Alive")
	client := &http.Client{}
	var resp *http.Response
	resp, err = client.Do(request)
	if err != nil {
		log.Println("client do error")
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Println("read resp error")
		return nil, err
	}
	return body, nil
}
